<?php
namespace app\user\controller\mall;

use app\common\model\mall\shop\Shop;
use app\common\model\mall\order\Order;
use app\common\model\mall\goods\Goods;
use think\Db;

/**
 * 控制台
 *
 * @icon fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Base
{
    // 初始化
    public function _initialize() {
        parent::_initialize();

    }

    /**
     * 获取当前登录用户买家信息
     */
    public function getBuyerInfo($user_id='')
    {
        $buyer = [];
        if($user_id=='') $user_id = $this->auth->id;
        //不统计虚拟的
        $buyer['order_count'] = Order::where(["prom_type"=>["<>", 5],"user_id" => $user_id])->count();
        //待付款数量
        $waitPay = Order::where(["prom_type"=>["<>", 5],"user_id" => $user_id, "status"=>"unpay"])->count();
        $buyer['waitPay'] = $waitPay;
        //待发货数量
        $waitSend = Order::where(["prom_type"=>["<>", 5],"user_id" => $user_id, "status"=>'undeliver'])->count();
        $buyer['waitSend'] = $waitSend;
        //待收货数量
        $waitReceive = Order::where(["prom_type"=>["<>", 5],"user_id" => $user_id, "status"=>'unreceive'])->count();
        $buyer['waitReceive'] = $waitReceive;

        $canceleds = Order::where(["prom_type"=>["<>", 5],"user_id" => $user_id, "status"=>'canceled'])->count();
        $buyer['canceleds'] = $canceleds;
        $rejecteds = Order::where(["prom_type"=>["<>", 5],"user_id" => $user_id, "status"=>'rejected'])->count();
        $buyer['rejecteds'] = $rejecteds;

        //退换货数
        $buyer['return_count'] = db('mall_order_refund')->where(['refundTo'=>$user_id])->count();

        //获取商品收藏数量
        $buyer['collect_count'] = db('mall_user_favorite')->where('user_id', $user_id)->count();
        $buyer['collect_goods'] = db('mall_user_favorite')->where(['user_id'=>$user_id,'type'=>'goods'])->count();
        $buyer['collect_shop'] = db('mall_user_favorite')->where(['user_id'=>$user_id,'type'=>'shop'])->count();

        $commentLogic = new \app\common\model\mall\goods\Appraise;
        //待评论数
        $buyer['uncomment_count'] = $commentLogic->where(["user_id"=>$user_id,"goodsraty"=>0,"serviceraty"=>0,"timeraty"=>0])->count();
        //已评论数
        $buyer['comment_count'] = $commentLogic->where(["user_id"=>$user_id,"goodsraty"=>['>',0],"serviceraty"=>['>',0],"timeraty"=>['>',0]])->count();

        return $buyer;

    }

    /**
     * 获取当前登录用户卖家信息
     */
    public function getSellerInfo($user_id='')
    {
        if($user_id=='') $user_id = $this->auth->id;
        $shop = Shop::where("user_id",$user_id)
            ->field('money,noSettledOrderFee,paymentMoney,id,shopImg,name,shopAddress,shopQQ,shopTel,serviceStartTime,serviceEndTime,areaIds,bankAreaIds,status')
            ->find();
        if(!empty($shop)){
            if($shop["status"] != "normal"){
                $this->error("店铺未启用!");
            }else{
                $data = $this->getShopSummary($shop);
                return $data;

            }
        }else{
            $this->error("未申请店铺，请申请入驻!", addon_url('mall/shop/join'));
        }
    }

    /**
     * 获取卖家中心信息
     */
    public function getShopSummary($shop){
        $shop_id = $shop['id'];
        //认证
        $accreds = $shop::shopAccreds($shop_id);
        $shop['accreds'] = $accreds;

        $stat = array();
        /**********今日动态**********/
        //今日销售金额
        $stat['saleMoney'] = Order::where(['status'=>['in',["undeliver","unreceive","unappraise","finished"]],'shop_id'=>$shop_id])->whereTime('createtime', 'today')->sum("goodsMoney");
        //今日订单数
        $stat['orderCnt'] = Order::where(['status'=>['in',["undeliver","unreceive","unappraise","finished"]],'shop_id'=>$shop_id])->whereTime('createtime', 'today')->count();
        //待发货订单
        $stat['waitDeliveryCnt'] = Order::where(['shop_id'=>$shop_id,'status'=>'undeliver'])->count();
        //待收货订单
        $stat['waitReceiveCnt'] = Order::where(['shop_id'=>$shop_id,'status'=>'unreceive'])->count();
        //取消/拒收
        $stat['cancelCnt'] = Order::where(['status'=>['in',["canceled","rejected"]],'shop_id'=>$shop_id])->count();
        //库存预警
        $shop_goods_ids = Goods::where("shop_id",$shop_id)->column("id");;
        $shop_goods_ids = implode(",", $shop_goods_ids );
        $goodsn = Goods::where('shop_id ='.$shop_id.' and goodsstock <= warnstock and specis = 0 and warnstock>0')->cache('stockWarnCnt1'.$shop_id,600)->count();
        $specsn = db('mall_goods_salespec')->where('goods_id in('.$shop_goods_ids.') and specstock <= warnstock and warnstock>0')->cache('stockWarnCnt2'.$shop_id,600)->count();
        $stat['stockWarnCnt'] = $goodsn+$specsn;

        /**********商品信息**********/
        //商品总数
        $stat['goodsCnt'] = Goods::where(['shop_id'=>$shop_id])->cache('goodsCnt'.$shop_id,600)->count();
        //上架商品
        $stat['onSaleCnt'] = Goods::where(['shop_id'=>$shop_id,'goodsStatus'=>1])->cache('onSaleCnt'.$shop_id,600)->count();
        //待审核商品
        $stat['waitAuditCnt'] = Goods::where(['shop_id'=>$shop_id,'goodsstatus'=>0])->cache('waitAuditCnt'.$shop_id,600)->count();
        //仓库中的商品
        $stat['unSaleCnt'] = Goods::where(['shop_id'=>$shop_id,'goodsstatus'=>0])->cache('unSaleCnt'.$shop_id,600)->count();
        //违规商品
        $stat['illegalCnt'] = Goods::where(['shop_id'=>$shop_id,'status'=>"illegal"])->cache('illegalCnt'.$shop_id,600)->count();
        //今日新品
        $stat['newGoodsCnt'] = Goods::where(['shop_id'=>$shop_id,'goodsstatus'=>1,'newis'=>1])->cache('newGoodsCnt'.$shop_id,600)->count();

        /**********订单信息**********/
        //待付款订单
        $stat['orderNeedpayCnt'] = Order::where(['shop_id'=>$shop_id,'status'=>'unpay'])->count();
        //待结束订单
        $stat['orderWaitCloseCnt'] = Order::where(['shop_id'=>$shop_id,'status'=>'unappraise','closedis'=>0])
            ->cache('orderWaitCloseCnt'.$shop_id,600)->count();
        //退货退款订单
        $stat['orderRefundCnt'] = Order::alias('o')
            ->join('mall_order_refund orf','orf.order_id=o.id')
            ->where(['shop_id'=>$shop_id,'refundStatus'=>0,'o.status'=>['in',['cancel','reject']]])->count();
        //待评价订单
        $stat['orderWaitAppraisesCnt'] = Order::where(['shop_id'=>$shop_id,'status'=>'unappraise','appraiseis'=>0])
            ->cache('orderWaitAppraisesCnt'.$shop_id,600)->count();
        // 投诉订单数
        $stat['complainNum'] = db('mall_order_complain')
            ->where(['respondTargetId'=>$shop_id,'complainStatus'=>1])->count();

        // 近七天销售排行
        $start = date('Y-m-d H:i:s',strtotime("-7 day"));
        $end = date('Y-m-d H:i:s');
        $stat['goodsTop'] = [];
        $stat['goodsTop'] = $rs = db('mall_order_goods')->alias('og')
            ->join('__MALL_ORDER_ORDER__ o','og.order_id=o.id','LEFT')
            ->join('__MALL_GOODS_GOODS__ g','og.goods_id=g.id','LEFT')
            ->where('o.createtime','between',[$start,$end])
            ->where('o.status','in',["undeliver","unreceive","unappraise","finished"])
            ->where('(payType=0 or (payType=1 and payis=1)) and o.shop_id='.$shop_id)
            ->order('og.goodsNum desc')->group('og.goods_id')
            ->field('og.goods_id,g.goodsname,goodsSn,sum(og.goodsNum) goodsNum,g.goodsImg')
            ->limit(10)->select();

        return ['shop'=>$shop->toArray(),'stat'=>$stat];
    }

    /**
     * 获取订单统计数据
     * @return mixed
     * @throws Exception
     */
    public function getOrders(){
        $data = cache('orderData');
        if(empty($data)){
            $date = $this->request->post('date', '');
            if ($date) {
                list($start, $end) = explode(' - ', $date);

                $starttime = strtotime($start);
                $endtime = strtotime($end);
            } else {
                $starttime = \fast\Date::unixtime('day', 0, 'begin');
                $endtime = \fast\Date::unixtime('day', 0, 'end');
            }
            $totalseconds = $endtime - $starttime;

            $format = '%Y-%m-%d';
            if ($totalseconds > 86400 * 30 * 2) {
                $format = '%Y-%m';
            } else if ($totalseconds > 86400) {
                $format = '%Y-%m-%d';
            } else {
                $format = '%H:00';
            }
            $orderlist = Order::where('createtime','between time',[$starttime,$endtime])
                ->field('orderSrc,count(id) orderNum, 
                    MIN(createtime) AS min_createtime, MAX(createtime) AS max_createtime, 
                    DATE_FORMAT(FROM_UNIXTIME(createtime), "' . $format . '") AS order_date')
                ->where('(payType=0 or (payType=1 and payis=1)) and shop_id='. cookie('shop_id'))
                ->order('createtime asc')
                ->group('orderSrc')->select();

            //构建横轴数组
            if ($totalseconds > 84600 * 30 * 2) {
                $starttime = strtotime('last month', $starttime);
                while (($starttime = strtotime('next month', $starttime)) <= $endtime) {
                    $column[] = date('Y-m', $starttime);
                }
            } else if ($totalseconds > 86400) {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("Y-m-d", $time);
                    $time += 86400;
                }
            } else {
                for ($time = $starttime; $time <= $endtime;) {
                    $column[] = date("H:00", $time);
                    $time += 3600;
                }
            }
            $list = array_fill_keys($column, 0);
            $orderlist = collection($orderlist)->toArray();
            foreach ($orderlist as $k => $v) {
                //构建纵轴数组
                $list[$v['orderSrc']][$v['order_date']] = $v['orderNum'];
            }

            //计算纵轴总数
            $orderSrcs = [1,2,3,4,5];
            foreach($column as $v){
                $total = 0;
                foreach($orderSrcs as $p){
                    $pv = isset($list[$p][$v]) ? $list[$p][$v] : 0;
                    $total = $total + (float)$pv;
                }
                $list['total'][$v] = $total;
            }
            $rdata = ['column' => $column, "orderList" => $list, "orderSrc" => \app\common\model\mall\order\Order::getOrdersrcList()];
            cache('orderData',$rdata,7200);
        }else{
            $rdata = cache('orderData');
        }
        return $rdata;
    }

    /**
     * 实现钩子方法
     * @return string
     */
    public function addHtmlRow()
    {
        $htmlRow = 'view/hook/user_dashboard_after';
        return $htmlRow;
    }

}
